package com.haitaoit.chengquan.module.home.activity.zhaopin;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.home.adapter.RecruitAdapter;
import com.haitaoit.chengquan.module.home.model.RecruitListModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class RecruitActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.pull_to_refresh_scrollview)
    PullToRefreshScrollView pullrefreshscrollview;
    @ViewInject(R.id.recruit_right)
    TextView recruit_right;

    private ScrollView mScrollView;
    private LinearLayout null_information_layout;
    private MyListView listView;
    private EditText search_et;


    private boolean isFrist = true;
    private int page = 1;
    private String recruit_type = "1";
    private RecruitAdapter adapter;
    private String mType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recruit);
        ViewUtils.inject(this);

        mType = PreferenceUtils.getPrefString("account_type", "");
        View view = LayoutInflater.from(this).inflate(R.layout.scrollview_listview_layout2, null);
        findViewById(R.id.search_LL).setVisibility(View.VISIBLE);
        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        listView = (MyListView) view.findViewById(R.id.scrollview_listview);
        search_et = (EditText) findViewById(R.id.search_et);
        search_et.setHint("请输入搜索内容...");
        findViewById(R.id.search_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setSearch();
            }
        });

        search_et.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_SEARCH){

// 先隐藏键盘
                    ((InputMethodManager) search_et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    RecruitActivity.this
                                            .getCurrentFocus()
                                            .getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    setSearch();

//跳转activity
//                    Intent intent = new Intent();
//                    intent.setClass(getActivity(), SearchResultActivity.class);
//                    startActivity(intent);
//
//// 将查询的数据插入数据库
//
//                    mDbHelper.insert_search_history(searchText.getText().toString(), getStringDate());

                    return true;
                }
                return false;
            }
        });



        pullrefreshscrollview.setPullLoadEnabled(true);
        pullrefreshscrollview.setPullRefreshEnabled(true);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        adapter = new RecruitAdapter(this);
        adapter.setType(recruit_type);
        adapter.setBackCall(backCall);
        listView.setAdapter(adapter);
        httpGetjob_information_list(Constant.Getrecruitment_information_list);

        if (TextUtils.equals(mType,"1")||TextUtils.isEmpty(mType)){
            recruit_right.setVisibility(View.INVISIBLE);
        }else {
            recruit_right.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        mType = PreferenceUtils.getPrefString("account_type", "");



    }

    private void setSearch(){
        if (search_et.getText().toString().equals("")) {
            ToastUtils.showToast("输入搜索内容！");
        } else {
            isFrist = true;
            page = 1;
            if ("1".equals(recruit_type)) {
                httpGetjob_information_list(Constant.Getrecruitment_information_list);
            } else if ("2".equals(recruit_type)) {
                httpGetjob_information_list(Constant.Getjob_information_list);
            }
        }
    }

    // 发布成功返回刷新
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode == 10 && resultCode == 1) {
//            isFrist = true;
//            page = 1;
//            if ("1".equals(recruit_type)) {
//                httpGetjob_information_list(Constant.Getrecruitment_information_list);
//            } else if ("2".equals(recruit_type)) {
//                httpGetjob_information_list(Constant.Getjob_information_list);
//            }
//        }
//        super.onActivityResult(requestCode, resultCode, data);
//    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            int position = (Integer) obj[0];
            Intent intent = new Intent();
            switch (which) {
                case R.id.job_itemll:
                    if (TextUtils.equals(recruit_type,"1")) {
                        intent.setClass(RecruitActivity.this, RecruitCompanyActivity.class);
                    } else {
                        intent.setClass(RecruitActivity.this, RecruitPersonalActivity.class);
                    }
                    intent.putExtra("id", adapter.getList().get(position).getId());
                    startActivity(intent);
                    break;
            }
            super.deal(which, obj);
        }
    };

    @OnClick({R.id.left, R.id.recruit_right, R.id.recruit_rb1, R.id.recruit_rb2,})
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.left:
//                intent.setClass(RecruitActivity.this, MainTabActivity.class);
//                intent.putExtra("index", 1);
//                //                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivity(intent);
                //TODO:不能单纯的finsh，第一个界面没办法展示数据
                finish();
                break;
            case R.id.recruit_right:
                if (TextUtils.equals(mType,"1")||TextUtils.isEmpty(mType)) {
                    intent.setClass(RecruitActivity.this, JobSendActivity.class);
                } else  {
                    intent.setClass(RecruitActivity.this, RecruitPeopleActivity.class);
                }
//                startActivityForResult(intent, 10);
                startActivity(intent);
                break;
            //企业招聘
            case R.id.recruit_rb1:
                if (TextUtils.equals(mType,"1")||TextUtils.isEmpty(mType)){
                    recruit_right.setVisibility(View.INVISIBLE);
                }else {
                    recruit_right.setVisibility(View.VISIBLE);
                }
                recruit_type = "1";
                isFrist = true;
                page = 1;
                recruit_right.setText(getString(R.string.QMyAddressActivity_title_right));
                adapter.setType(recruit_type);
                httpGetjob_information_list(Constant.Getrecruitment_information_list);
                break;
            //个人求职
            case R.id.recruit_rb2:
                if (TextUtils.equals(mType,"1")||TextUtils.isEmpty(mType)){
                    recruit_right.setVisibility(View.VISIBLE);
                }else {
                    recruit_right.setVisibility(View.INVISIBLE);
                }
                recruit_type = "2";
                isFrist = true;
                page = 1;
                recruit_right.setText("发布求职");
                adapter.setType(recruit_type);
                httpGetjob_information_list(Constant.Getjob_information_list);

                break;
        }
        // 收起键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(search_et.getWindowToken(), 0);
    }

    private void httpGetjob_information_list(String url) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("name", search_et.getText().toString()));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("name", search_et.getText().toString());
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                List<RecruitListModel> new_list = new ArrayList<RecruitListModel>();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<RecruitListModel>();
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<RecruitListModel>>() {
                                    }.getType());
                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<RecruitListModel>();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            adapter.setList(new_list);
                            adapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<RecruitListModel> allList = adapter.getList();
                        allList.addAll(new_list);
                        adapter.setList(allList);
                        adapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List<RecruitListModel> rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = true;
        page = 1;
        if (TextUtils.equals(recruit_type,"1")) {
            httpGetjob_information_list(Constant.Getrecruitment_information_list);
        } else {
            httpGetjob_information_list(Constant.Getjob_information_list);
        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
        if (TextUtils.equals(recruit_type,"1")) {
            httpGetjob_information_list(Constant.Getrecruitment_information_list);
        } else {
            httpGetjob_information_list(Constant.Getjob_information_list);
        }
    }
}
